<template>
    <div class="production-plan">
   <!-- <el-upload
       class="upload-demo"
       ref="uploadRef"
       action="#"
       :auto-upload="false"
       :on-change="handleFileChange"
       :on-success="handleUploadSuccess"
       :on-error="handleUploadError"
       accept=".xlsx,.xls"
     >
       <el-button type="primary" slot="trigger">导入</el-button>
       <el-tooltip content="支持.xlsx和.xls格式文件" placement="top">
         <i class="el-icon-question"></i>
       </el-tooltip>
     </el-upload>
     <el-button type="primary" @click="importData" :disabled="!selectedFile">上传</el-button> -->
      <h3 class="title">到货检验信息详情页</h3>
  
      <!-- 基本信息 -->
      <el-descriptions
        class="arrival-detail"
        :column="3"
        border
        title="到货检验信息"
      >
        <el-descriptions-item label="检验主题">{{ formData.inspectionSubject }}</el-descriptions-item>
        <el-descriptions-item label="检验单号">{{ formData.inspectionOrderNumber }}</el-descriptions-item>
        <el-descriptions-item label="检验日期">{{ formData.inspectionDate }}</el-descriptions-item>
        <el-descriptions-item label="检验人员">{{ formData.inspectionPersonnel }}</el-descriptions-item>
        <el-descriptions-item label="所在部门">{{ formData.department }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ formData.contactInformation }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ formData.remarks }}</el-descriptions-item>
      </el-descriptions>
  
      <!-- 父件信息 -->
      <h2>采购信息</h2>
      <el-descriptions
        class="arrival-detail"
        :column="3"
        border
        title="采购信息"
      >
        <el-descriptions-item label="采购单号">{{ formData.purchaseOrderNumber }}</el-descriptions-item>
        <el-descriptions-item label="采购日期">{{ formData.purchaseDate }}</el-descriptions-item>
        <el-descriptions-item label="供应商名称">{{ formData.supplierName }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ formData.contactPerson }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ formData.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="采购人员">{{ formData.purchasingPersonnel }}</el-descriptions-item>
        <el-descriptions-item label="采购部门">{{ formData.purchasingDepartment }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ formData.contactMethod }}</el-descriptions-item>
        <el-descriptions-item label="关联项目">{{ formData.relatedProject }}</el-descriptions-item>
      </el-descriptions>
      <!-- 附件 -->
           <div id="app">
    <el-card>
      <template #header>
        <div class="flex justify-between items-center">
          <span>MinIO 文件上传</span>
        </div>
      </template>
      <el-form ref="formRef1" :model="formData1" label-width="100px">
        <el-form-item label="选择文件">
          <el-upload ref="uploadRef" action="https://localhost:7269/api/FileUpload/UploadFile" :headers="headers"
            :on-success="handleSuccess" :on-error="handleError" :show-file-list="false" :http-request="customRequest">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">上传文件</el-button>
        </el-form-item>
      </el-form>
      <el-alert v-if="message" :message="message" :type="messageType" :closable="false" style="margin-top: 20px" />
    </el-card>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="key" label="文件名称" width="200" />
      <el-table-column prop="lastModified" label="创建时间" width="200">
        <template #default="scope">
          {{ new Date(scope.row.lastModified).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="size" label="文件大小" min-width="200" />
      <el-table-column fixed="right" label="操作" min-width="200">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="openDeleteDialog(scope.row.key)">
            删除文件
          </el-button>
          <el-button link type="primary" size="small" @click="download(scope.row.key)">下载文件</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="isDeleteDialogVisible" title="删除确认" @close="closeDeleteDialog">
      <p>确定要删除该文件吗？</p>
      <template #footer>
        <el-button @click="closeDeleteDialog">取消</el-button>
        <el-button type="primary" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="isDownloadDialogVisible" title="文件下载">
      <template #content>
        <el-progress :percentage="downloadProgress" :status="downloadStatus"></el-progress>
      </template>
      <template #footer>
        <el-button @click="closeDownloadDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, watch } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { useRouter, useRoute } from 'vue-router';
  import { Materialread, Materialwrite } from '@/axios/axiosHelper';
  import axios from 'axios';
  import { th } from 'element-plus/es/locales.mjs';
  
  const formRef = ref(null);
  const currentUser = ref("admin");
  const router = useRouter();
  const route = useRoute();
  
  // 主表单数据
  const formData = reactive({
        "basicInfoid":  route.params.id,
    "inspectionSubject": "",
    "inspectionOrderNumber": "",
    "inspectionDate": "",
    "inspectionPersonnel":  currentUser.value,
    "department": "",
    "contactInformation": "",
    "purchaseOrderNumber": "",
    "purchaseDate": "",
    "supplierName": "",
    "contactPerson": "",
    "contactPhone": "",
    "purchasingPersonnel": "",
    "purchasingDepartment": "",
    "contactMethod": "",
    "relatedProject": "",
    "remarks": "",
    "isDel": true
  });

  const attachments = ref([
    { name: '新建文本文档.PDF', size: '0 Bytes', uploadTime: '2022-08-11 17:45:27', url: '#' },
    { name: '新建文本文档.PDF', size: '0 Bytes', uploadTime: '2022-08-11 17:45:27', url: '#' },
    { name: '新建文本文档.PDF', size: '0 Bytes', uploadTime: '2022-08-11 17:45:27', url: '#' },
  ]);

  function viewFile(file) {
    // 这里可以实现预览功能，比如 window.open(file.url)
    window.open(file.url, '_blank');
  }

  function downloadFile(file) {
    // 这里可以实现下载功能，比如 window.open(file.url)
    window.open(file.url, '_blank');
  }

  const getProductionById = (basicInfoid) => {
    console.log('查看反填数据:', basicInfoid);
    Materialread.get('f-read/api/Arrival/FTBasicInfo', {
        params:{
            BasicInfoid: route.query.basicInfoid
        }
      })
      .then(res=>{
        formData.id = res.data.data[0].id;
        formData.inspectionSubject = res.data.data[0].inspectionSubject;
        formData.inspectionOrderNumber = res.data.data[0].inspectionOrderNumber;
        formData.inspectionDate = res.data.data[0].inspectionDate;
        formData.inspectionPersonnel = res.data.data[0].inspectionPersonnel;
        formData.department = res.data.data[0].department;
        formData.contactInformation = res.data.data[0].contactInformation;
        formData.purchaseOrderNumber = res.data.data[0].purchaseOrderNumber;
        formData.purchaseDate = res.data.data[0].purchaseDate;
        formData.supplierName = res.data.data[0].supplierName;
        formData.contactPerson = res.data.data[0].contactPerson;
        formData.contactPhone = res.data.data[0].contactPhone;
        formData.purchasingPersonnel = res.data.data[0].purchasingPersonnel;
        formData.purchasingDepartment = res.data.data[0].purchasingDepartment;
        formData.contactMethod = res.data.data[0].contactMethod;
        formData.relatedProject = res.data.data[0].relatedProject;
        formData.remarks = res.data.data[0].remarks;
        formData.modelValue = res.data.data[0];
        console.log('反填数据:', res.data);
      })
  };

  // // 保存主表单
  const addjihau = () => {
    axios.post('https://localhost:7229/api/Process/UpdateProcess', formData)
    .then(response => {
     if (response.data.code === 200) {
       ElMessage.success('过程监控修改成功');
       console.log(response.data.data);
       router.push("/GetProcess");
    } else {
       ElMessage.error(`过程监控修改失败：${response.data.message}`);
    }
    })
  };

  onMounted(()=>{
    getProductionById();
  })
// 处理文件变化
const handleFileChange = (file, fileList) => {
  selectedFile.value = file.raw;
  console.log('选择的文件:', selectedFile.value);
};

// 处理上传成功
const handleUploadSuccess = (response) => {
  if (response && response.code === 200) {
    ElMessage.success('导入成功');
    ShowMaterials();
    uploadRef.value.clearFiles();
    selectedFile.value = null;
  } else {
    ElMessage.error(`导入失败：${response.message || '未知错误'}`);
  }
  uploadLoading.value = false;
};

// 处理上传错误
const handleUploadError = (error) => {
  console.error('上传错误:', error);
  ElMessage.error('导入失败，请检查网络或文件格式');
  uploadLoading.value = false;
};

// 执行上传
const importData = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请选择要导入的文件');
    return;
  }

  uploadLoading.value = true;
  
  try {
    const formData = new FormData();
    formData.append('file', selectedFile.value);
    
    const response = await axios.post(
      'https://localhost:7238/api/Arrival/ImportExcel', 
      formData,
      {
        headers: { 
          'Content-Type': 'multipart/form-data'
        }
      }
    );
    
    handleUploadSuccess(response.data);  
  } catch (error) {
    console.error('导入错误:', error);
    if (axios.isAxiosError(error)) {
      if (error.response) {
        ElMessage.error(`导入失败，状态码: ${error.response.status}`);
      } else {
        ElMessage.error('导入失败，请检查网络连接');
      }
    } else {
      ElMessage.error('导入失败，请检查文件格式或联系管理员');
    }
    uploadLoading.value = false;
  }
};
 const download = async (key) => {
  isDownloadDialogVisible.value = true;
  downloadProgress.value = 0;
  downloadStatus.value = 'active';
  try {
    const response = await axios.get(`/api/FileUpload/DownloadFile?objectName=${key}`, {
      responseType: 'blob',
      onDownloadProgress: (progressEvent) => {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        downloadProgress.value = percentCompleted;
      }
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', key);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    downloadStatus.value = 'success';
  } catch (error) {
    console.error('文件下载失败:', error);
    message.value = '文件下载失败: ' + (error.response?.data?.error || error.message);
    messageType.value = 'error';
    downloadStatus.value = 'exception';
  }
};

const listObjects = async () => {
  axios.get("https://localhost:7212/api/FileUpload/ListObjectsInOneBucket")
    .then((res) => {
      tableData.value = res.data;
      console.log("查询成功", res.data);
    })
    .catch((err) => {
      console.log(err);
    });
};

const headers = {
  'Content-Type': 'multipart/form-data'
};

const customRequest = async (options) => {
  const formData1 = new FormData();
  formData1.append('file', options.file);
  const response = await axios.post(options.action, formData1, {
    headers: headers
  });
  options.onSuccess(response.data);
  if (response.data != null) {
    alert("添加成功");
    return;
  } else {
    alert("添加失败");
    return;
  }
};

const handleError = (error) => {
  message.value = '上传失败: ' + (error.response?.data?.error || error.message);
  messageType.value = 'error';
};

const submitForm = () => {
  uploadRef.value.submit();
};

const openDeleteDialog = (key) => {
  currentDeleteKey.value = key;
  isDeleteDialogVisible.value = true;
};

const closeDeleteDialog = () => {
  isDeleteDialogVisible.value = false;
  currentDeleteKey.value = '';
};

const confirmDelete = () => {
  axios.delete("https://localhost:7212/api/FileUpload/DeleteObjectInOneBucket", {
    params: {
      objectName: currentDeleteKey.value
    }
  })
    .then((res) => {
      console.log("删除成功", res.data);
      message.value = '文件删除成功';
      messageType.value = 'success';
      listObjects();
      closeDeleteDialog();
    })
    .catch((err) => {
      console.log(err);
      message.value = '文件删除失败: ' + (err.response?.data?.error || err.message);
      messageType.value = 'error';
      closeDeleteDialog();
    });
};

const closeDownloadDialog = () => {
  isDownloadDialogVisible.value = false;
  downloadProgress.value = 0;
  downloadStatus.value = '';
};
 
 

  </script>
  
  <style scoped>
  .production-plan {
    padding: 20px;
  }
  
  .title {
    text-align: center;
    margin-bottom: 20px;
  }
  
  .sub-title {
    margin: 20px 0 10px;
    font-size: 16px;
    font-weight: 500;
  }
  
  .detail-section,
  .attachment-section {
    margin-top: 20px;
  }
  
  .el-table {
    margin-top: 10px;
  }
  </style>